package com.hht;

import java.util.concurrent.Semaphore;

/**
 * 银行营业部有两个柜台给三个人提供服务
 * 应用场景 资源有限 最多同时处理多少个任务 可以灵活控制
 */
public class SemaphoreDemo {

	public static void main(String[] args) {
		//最多允许多少个并发线程来进入这个区域
		Semaphore semaphore = new Semaphore(2);
		
		Person p1 = new Person(semaphore, "P1");
		p1.start();
		
		Person p2 = new Person(semaphore, "P2");
		p2.start();
		
		Person p3 = new Person(semaphore, "P3");
		p3.start();
	}
}

class Person extends Thread {
	
	private Semaphore semaphore;
	
	public  Person(Semaphore semaphore, String name) {
		setName(name);
		this.semaphore = semaphore;
	}
	
	public void run() {
		System.out.println(getName() + " is waiting...");
		try {
			//每个线程过来，首先要获取许可证
			semaphore.acquire();
			System.out.println(getName() + " is servicing...");
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(getName() + " is done!");
		//操作结束，要释放许可证
		semaphore.release();
	}
}
